package com.system.blogAdmin.blog.controller;

import com.cnc.common.web.ezPage.EzPage;
import com.cnc.common.web.ezPage.EzPageParam;
import com.cnc.common.web.ezPage.PageUtils;
import com.cnc.common.web.util.MessageBox;
import com.system.blogAdmin.auth.entity.User;
import com.system.blogAdmin.blog.dto.ArticleDto;
import com.system.blogAdmin.blog.dto.ArticleForm;
import com.system.blogAdmin.blog.dto.SearchDto;
import com.system.blogAdmin.blog.dto.enumdto.BlogType;
import com.system.blogAdmin.blog.entity.BlogArticle;
import com.system.blogAdmin.blog.service.BlogCategoryService;
import com.system.blogAdmin.blog.service.BlogArticleService;
import com.system.blogAdmin.utils.Base64Utils;
import com.system.blogAdmin.utils.DtoUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 作者： cnc
 * 创建时间：2017-06-22.
 * 版本：1.0
 */
@Controller
@RequestMapping(value = {"/essays","/article","/bug","/blogArticle"})
public class BlogArticleController {

    @Autowired
    BlogArticleService blogArticleService;
    @Autowired
    BlogCategoryService blogCategoryService;
    /**
     * 根据类型获取界面
     * @param type
     * @param model
     * @return
     */
    @RequestMapping(value = "/index/{type}",method = RequestMethod.GET)
    public String index(@PathVariable String type,Model model){
        Map<String,Object> map = new HashMap<String , Object>();
        map.put("type",type);
        map.put("contentType", chioceType(type));
        model.addAttribute("map", map);
        return "blogAdmin/blog/blog_article_index";
    }

    /**
     * 根据类型获取文章
     * @param contentType
     * @return
     */
    @RequestMapping(value = "/list/{contentType}", method = RequestMethod.POST,produces = "application/json;charset=utf-8;")
    @ResponseBody
    public EzPage<ArticleDto> blogArticleList1 (EzPageParam pageParam,@RequestParam(required = false) Long id, String title,String type,@PathVariable String contentType){
        Map<String , Object> map  = new HashMap<String, Object>();
        if(id!=null&&title.length()>0&&type.length()>0){
            System.out.println("ID:"+id+"Title:"+title+"Type:"+type);
            if(type.equals("类别")){
                map.put("categoryId",id);
                map.put("contentType", contentType);
                map.put("contentType", chioceType(contentType));
            }else if(id == null && title.length() > 0 && type.length()==0){
                map.put("content", title);
            }else{
                map.put("id", id);
            }
        }else{
            map.put("contentType", chioceType(contentType));
        }
      return  PageUtils.convertPageBean(DtoUtils.ArticleToBlog(blogArticleService.listPage(PageUtils.convert(pageParam), map)));
    }
    /**
     * 添加文章
     * @return
     */
    @RequestMapping(value = "/add", method = RequestMethod.POST,produces = "application/json;charset=utf-8;")
    @ResponseBody
    public MessageBox addArticle(ArticleForm articleForm){

        System.out.println("传值:" + articleForm.toString());
        Subject subject = SecurityUtils.getSubject();
        User u = (User) subject.getPrincipal();
        if(u!=null){
            BlogArticle blogArticle = new BlogArticle();
            blogArticle.setId(articleForm.getId());
            blogArticle.setCreateName(u.getAccount());
            SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
            String dateString = formatter.format(new Date());
            blogArticle.setCreateTime(dateString);
            blogArticle.setCreateId(Integer.parseInt(u.getId().toString()));
            blogArticle.setLabel(articleForm.getLabel());
            blogArticle.setContent(articleForm.getContent());
            blogArticle.setContentType(articleForm.getContentType());
            blogArticle.setTitle(articleForm.getTitle());
            String catName = blogCategoryService.getById(articleForm.getPid()).getName();
            blogArticle.setCategoryName(catName);
            blogArticle.setCategoryId(Integer.parseInt(articleForm.getPid().toString()));
            blogArticleService.create(blogArticle);
            return MessageBox.getSuccessMsg("添加成功！");
        }else{
            return MessageBox.getErrorMsg("出错！");
        }
    }

    /**
     * 删除文章
     * @param ids
     * @return
     */
    @RequestMapping(value = "/delete",method = RequestMethod.POST,produces = "application/json;charset=utf-8")
    @ResponseBody
    public MessageBox deleteAritcle(@RequestParam("ids[]")List<Long> ids){
        if(ids.size()>0){
            blogArticleService.deleteByIds(ids);
        }
        return MessageBox.getSuccessMsg("删除成功！");
    }

    /**
     * 修改文章
     */
    @RequestMapping(value = "/update",method = RequestMethod.POST,produces = "application/json;charset=utf-8;")
    @ResponseBody
    public MessageBox updateAricle(ArticleForm articleForm){
        System.out.println("传值:" + articleForm.toString());
        Subject subject = SecurityUtils.getSubject();
        User u = (User) subject.getPrincipal();
        if(u!=null){
            
            BlogArticle blogArticle = new BlogArticle();
            blogArticle.setId(articleForm.getId());
            blogArticle.setModifyId(u.getId().toString());
            blogArticle.setLabel(articleForm.getLabel());
            blogArticle.setContent(articleForm.getContent());
            blogArticle.setContentType(articleForm.getContentType());
            blogArticle.setTitle(articleForm.getTitle());
            blogArticle.setRecommend(articleForm.getRecommend());
            blogArticle.setCategoryId(Integer.parseInt(articleForm.getPid().toString()));
            String catName = blogCategoryService.getById(articleForm.getPid()).getName();
            blogArticle.setCategoryName(catName);
            blogArticleService.update(blogArticle);
            return MessageBox.getSuccessMsg("修改成功！");
        }else{
            return MessageBox.getErrorMsg("出错！");
        }
    }

    /**
     * 延时搜索
     *
     * strValue   输入查询条件
     *
     */
    @RequestMapping(value = "/search",method = RequestMethod.POST, produces = "application/json;charset=utf-8;")
    @ResponseBody
    public List<SearchDto> getSearchDto (@RequestParam(required = false)String strValue,String contentType){

        if(strValue != "" && strValue.length()>0){
            List<SearchDto> searchDtoList = blogArticleService.getSearch(strValue,contentType);
            for (SearchDto searchDto : searchDtoList) {
                String str =searchDto.getTitle();
                if(str.length()>12){
                    searchDto.setTitle(strValue);
                }else{
                    searchDto.setTitle(str);
                }
            }
            return searchDtoList;
        }
        return null;
    }

    /**
     * 判断 博文类型
     * @param type
     * @return
     */
    public static String chioceType(String type){
        for (BlogType blogType : BlogType.values()) {
           if ( blogType.toString().equals(type) ){
               return blogType.getValue();
           }
        }
        return null;
    }
}
